package com.cooba.activitys.Living;

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.adapter.LivingDetailAdapter;
import com.cooba.bean.LivingDetailBean;
import com.cooba.bean.MyLivingBean;
import com.cooba.mqtt.MqttBroker;
import com.cooba.mqtt.PushService;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.BitmapZipUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.cooba.views.ProgressImageView;
import com.cooba.views.loadview.LoadViewHelper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import me.nereo.multi_image_selector.MultiImageSelector;

public class LivingDetailActivity extends AppCompatActivity {

    private ArrayList<LivingDetailBean.LivingDetailContent> myLivingList;
    private ScrollView my_living__detail_sv;
    private ImageButton my_living_detail_back_ib;
    private ImageView my_living_detail_add_iv;
    private LinearLayout my_living__detail_add_ll;
    private PullToRefreshListView rListView;
    private LivingDetailAdapter mAdapter;
    private LoadViewHelper helper;
    private boolean mIsFirstLoad = true;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String next_key = "0";
    private LivingDetailBean livingdetailbean;
    private HttpHandler<String> handler;
    private LayoutInflater li;
    private ProgressImageView imageView;
    private int i = 0;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private ArrayList<File> fileList = new ArrayList<>();
    private String live_id;
    private String title;
    private String pic;
    private LinearLayout my_living__detail_no_data_ll;
    private MyReceiver myReceiver;
    private MqttBroker mqttBroker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_living_detail);
        live_id = getIntent().getStringExtra("live_id");
        title = getIntent().getStringExtra("title");
        pic = getIntent().getStringExtra("pic");
        IntentFilter filter = new IntentFilter();
        filter.addAction("MQTT_ACTION");
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, filter);
        initView();
        initHeadView();
    }

    private void initHeadView() {
        View headerView = View.inflate(this, R.layout.living_head_view, null);
        View footerView = View.inflate(this, R.layout.footer_view_layout, null);
        TextView textView = (TextView) headerView.findViewById(R.id.living_head_view_big_title);
        my_living__detail_no_data_ll = (LinearLayout) headerView.findViewById(R.id.my_living__detail_no_data_ll);
        textView.setText(title);
        final ImageView imageView = (ImageView) headerView.findViewById(R.id.living_head_view_image);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        BitmapUtils bitmapUtils = new BitmapUtils(this);
        /**
         * 设置默认的图片展现、加载失败的图片展现
         */
        bitmapUtils.configDefaultLoadingImage(R.mipmap.default_icon1);
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.default_icon1);
        bitmapUtils.display(imageView, pic);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.56);
        LinearLayout.LayoutParams laParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
        laParams.width = width;
        laParams.height = height;
        imageView.setLayoutParams(laParams);
        my_living__detail_add_ll = (LinearLayout) headerView.findViewById(R.id.my_living__detail_add_ll);
        my_living__detail_add_ll.setVisibility(View.GONE);
        rListView.getRefreshableView().addHeaderView(headerView);
        //rListView.getRefreshableView().addFooterView(footerView);
        getMylivingDetail(true);
    }

    private void initView() {
        myLivingList = new ArrayList<>();
        my_living_detail_back_ib = (ImageButton) findViewById(R.id.my_living_detail_back_ib);
        my_living_detail_back_ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initPullTorefresh();
        helper = Utils.initLoadViewHelper(rListView);
//        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//        SharedPreferences.Editor editor = getSharedPreferences(PushService.TAG,
//                MODE_PRIVATE).edit();
//        String mDeviceID=tm.getDeviceId();
//        editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
//        editor.commit();
//        PushService.actionStart(getApplicationContext());
//
        new Thread(new Runnable() {
            @Override
            public void run() {
                int[] QOS_VALUES = {0};// 对应主题的消息级别
                String[] TOPICS = {live_id};
                mqttBroker = new MqttBroker();
                try {
                    mqttBroker.connect(TOPICS, QOS_VALUES, LivingDetailActivity.this);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void initPullTorefresh() {
        rListView = (PullToRefreshListView) findViewById(R.id.my_living_detail_lv);
        rListView.setPullRefreshEnabled(true);
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                getMylivingDetail(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getMylivingDetail(false);
            }
        });
        mAdapter = new LivingDetailAdapter(this, myLivingList);
        rListView.getRefreshableView().setAdapter(mAdapter);
    }

    private void getMylivingDetail(final boolean isFirst) {
//        if (mIsFirstLoad) {
//            helper.showLoading("正在加载...");
//        }
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        //params.addBodyParameter("user_id", login_id);
        params.addBodyParameter("liveId", live_id);
        if (isFirst) {
            next_key = "0";
        }
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urllivingcontentlist = ServerURL.httpUrl + ServerURL.livingcontentlist;
        handler = httpUtils.send(HttpRequest.HttpMethod.POST, urllivingcontentlist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取直播详情列表失败");
                Toast.makeText(LivingDetailActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
                rListView.setHasMoreData(false);
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取直播详情列表成功" + responseInfo.result);
                try {
                    livingdetailbean = new Gson().fromJson(responseInfo.result, LivingDetailBean.class);
                    if (livingdetailbean.getContentList() != null && livingdetailbean.getContentList().size() > 0) {
                        if (isFirst) {
                            mAdapter.setList(livingdetailbean.getContentList());
                        } else {
                            mAdapter.addMoreData(livingdetailbean.getContentList());
                        }
                        if (livingdetailbean.getNext_key() == null) {
                            next_key = String.valueOf(livingdetailbean.getContentList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = livingdetailbean.getNext_key();
                        }
                        if (livingdetailbean.getContentList().size() < 10) {
                            rListView.setHasMoreData(false);
                        }
//                        mIsFirstLoad = false;
//                        helper.restore();
                    } else {
                        if (isFirst) {
                            rListView.setHasMoreData(false);
                            my_living__detail_no_data_ll.setVisibility(View.VISIBLE);

                            //helper.showEmpty("暂时没有数据", "重新加载", false, null);
                        } else {
                            Toast.makeText(LivingDetailActivity.this, "没有更多数据啦", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } finally {

                    rListView.onPullDownRefreshComplete();
                    rListView.onPullUpRefreshComplete();

                }
            }
        });
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("MQTT_ACTION")) {
                String data = intent.getExtras().getString("mqtt_info");
                try {
                    LivingDetailBean listdata = new Gson().fromJson(data, LivingDetailBean.class);
                    Collections.reverse(listdata.getContentList());
                    mAdapter.addNewData(listdata.getContentList());
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver!=null){
            unregisterReceiver(myReceiver);
        }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mqttBroker.closeMqttClient();
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    }
}
